#include <bits/stdc++.h>
using namespace std;
int len;
string str;
int ss[400000];
int permutation[10][400000];
int per_cnt[10][400000];
int cnt;
int getNum(int* t) {
    int ret = 0;
    for (int i=0; i<len; ++i) {
        ret = ret*10 + t[len-i-1];
    }
    return ret;
}
bool vis[11];
inline int cmp(int* b) {
    int ret = 0;
    memset(vis, 0, sizeof(vis));
    for (int i=0; i<len; ++i) {
        if (i != b[i] && !vis[i]) {
            int z = 0;
            int c = i;
            while (!vis[c]) {
                vis[c] = true;
                c = b[c];
                ++z;
            }
            ret += (z-1);
        }
    }
    return ret;
}
void Init() {
    for (len=1; len<=9; ++len) {
        cnt = 0;
        int buf[len];
        for (int j=0; j<len; ++j) buf[j] = j;
        do {
            per_cnt[len][cnt] = cmp(buf);
            permutation[len][cnt] = getNum(buf);
            ++cnt;
        }while(next_permutation(buf, buf+len));
    }
}
int getFac(int a) {
    int ret = 1;
    for (int i=1; i<=a; ++i) {
        ret = (ret * i);
    }
    return ret;
}
int getSnum(int t) {
    int ret = 0;
    int z = len;
    while(z--) {
        ret = ret * 10 + str[t % 10] - '0';
        t = t / 10;
    }
    return ret;
}

int main(int argc, char** argv) {
#ifdef hai
    freopen("in.txt", "r", stdin);
#endif
    Init();
    int T;
    cin>>T;
    int n;
    char myss[11];
    while(T--) {
        scanf("%s %d", myss, &n);
        str = myss;
        len = str.length();
        sort(myss, myss+len);
        if (len==10) {
            printf("1000000000 1000000000\n");
            continue;
        }
        int x1=-1, x2=-1;
        cnt = getFac(len);
        int* perm = permutation[len];
        for (int p=0; p<cnt; ++p) {
            //printf("cmp: %d\n", cmp(t));
            if(str[perm[p]%10] != '0' && per_cnt[len][p] <= n) {
                ss[p] = getSnum(perm[p]);
                //printf("%d\n", ss[p]);
                if (x1==-1) x1 = p, x2 = p;
                else {
                    if (ss[p] < ss[x1]) x1 = p;
                    if (ss[x2] < ss[p]) x2 = p;
                }
            }
        }
        printf("%d %d\n", ss[x1], ss[x2]);
    }
    return 0;
}
